package com.xcm.controller;

import com.alibaba.fastjson.JSONObject;
import com.xcm.config.MyConfig;
import com.xcm.constant.BaseConstant;
import com.xcm.constant.FileConstants;
import com.xcm.constant.SysUserConstants;
import com.xcm.exception.ServiceException;
import com.xcm.model.SysUser;
import com.xcm.model.response.JsonResponseBuilder;
import com.xcm.model.vo.SysUserVo;
import com.xcm.page.PageInfo;
import com.xcm.service.SysUserService;
import com.xcm.util.CollectionsUtil;
import com.xcm.util.ExcelUtils;
import com.xcm.validator.SysUserValidator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 用户
 *
 * @author linqiang
 * @date 2018-04-13 9:15
 */
@Controller
@RequestMapping(value = "/sysUser")
public class SysUserController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private SysUserService sysUserService;

    /**
     * 新增用户
     *
     * @param sysUserJson 新增的用户对象JSON串
     * @param roleIds     角色id(多个以英文的逗号隔开)
     * @return
     */
    @RequestMapping(value = "/saveSysUser")
    @ResponseBody
    public Object saveSysUser(String sysUserJson, String roleIds) {
        try {
            if (StringUtils.isBlank(sysUserJson)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.VALIDATE_NO_SYS_USER);
            }
            JSONObject object = JSONObject.parseObject(sysUserJson);
            SysUser sysUser = JSONObject.toJavaObject(object, SysUser.class);
            String checkFormResult = SysUserValidator.validateFormSysUser(sysUser);
            //用户表单验证,失败返回对应的提示语句
            if (StringUtils.isNotBlank(checkFormResult)) {
                return JsonResponseBuilder.buildFail(checkFormResult);
            }
            //检查用户是否存在
            SysUser checkUniqueUser = sysUserService.getByUsername(sysUser.getUserName());
            if (null != checkUniqueUser) {
                return JsonResponseBuilder.buildFail(SysUserConstants.VALIDATE_USER_EXITS);
            }
            if (StringUtils.isBlank(sysUser.getSex())) {
                sysUser.setSex(SysUserConstants.SEX_FEMAIL);
            }
            int effectRow = sysUserService.save(sysUser, roleIds);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysUserConstants.SAVE_SUCCESS);
            }
        } catch (Exception e) {
            logger.error("SysUserController saveSysUser 新增用户失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysUserConstants.SAVE_FAIL);
    }

    /**
     * 修改用户
     *
     * @param sysUserJson 修改的用户对象JSON串
     * @param roleIds     角色id(多个以英文的逗号隔开)
     * @return
     */
    @RequestMapping(value = "/updateSysUser")
    @ResponseBody
    public Object updateSysUser(String sysUserJson, String roleIds) {
        try {
            if (StringUtils.isBlank(sysUserJson)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.VALIDATE_NO_SYS_USER);
            }
            JSONObject object = JSONObject.parseObject(sysUserJson);
            SysUserVo sysUserVo = JSONObject.toJavaObject(object, SysUserVo.class);
            if (null == sysUserVo) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
            }
            if (null == sysUserVo.getUserId()) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_NOT_ENOUGH);
            }
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserVo, sysUser);
            String checkFormResult = SysUserValidator.validateFormSysUser(sysUser);
            //用户表单验证,失败返回对应的提示语句
            if (StringUtils.isNotBlank(checkFormResult)) {
                return JsonResponseBuilder.buildFail(checkFormResult);
            }
            int effectRow = sysUserService.update(sysUser, roleIds);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysUserConstants.UPDATE_SUCCESS);
            }
        } catch (ServiceException e) {
            logger.error("SysUserController updateSysUser 修改用户失败：" + e.getMessage());
            return JsonResponseBuilder.buildFail(e.getMessage());
        } catch (Exception e) {
            logger.error("SysUserController updateSysUser 修改用户失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysUserConstants.UPDATE_FAIL);
    }

    /**
     * 根据id查询
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping(value = "/getById")
    @ResponseBody
    public Object getById(Integer userId) {
        if (null == userId) {
            return BaseConstant.MSG_PARAM_ERROR;
        }
        try {
            SysUserVo sysUserVo = sysUserService.getByIdVo(userId);
            if (null == sysUserVo) {
                return JsonResponseBuilder.buildFail(SysUserConstants.VALIDATE_USER_NOT_EXITS);
            }
            return JsonResponseBuilder.buildSuccess(sysUserVo);
        } catch (Exception e) {
            logger.error("SysUserController getById 根据id查询用户失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysUserConstants.GET_FAIL);
    }

    /**
     * 用户分页查询(可查询某角色下用户，可查询某部门下用户)
     *
     * @param departmentId 部门id
     * @param roleId       角色id
     * @param search       搜索的条件(姓名/手机/邮箱，模糊匹配其中任意一项)
     * @param pageNum      第几页
     * @param pageSize     每页几条
     * @return
     */
    @RequestMapping(value = "/listPage")
    @ResponseBody
    public Object listPage(Integer departmentId, Integer roleId, String search, Integer pageNum, Integer pageSize) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            if (null != departmentId) {
                paramMap.put("departmentId", departmentId.toString());
            }
            if (null != roleId) {
                paramMap.put("roleId", roleId.toString());
            }
            if (StringUtils.isNotBlank(search)) {
                paramMap.put("search", search);
            }
            PageInfo sysUserVoPage = sysUserService.listPage(paramMap,
                    pageNum == null ? super.pageNum : pageNum,
                    pageSize == null ? super.pageSize : pageSize);
            return JsonResponseBuilder.buildSuccess(sysUserVoPage);
        } catch (Exception e) {
            logger.error("SysUserController listPage 用户分页查询失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(BaseConstant.QUERY_FAIL);
    }

    /**
     * 用户集合查询
     *
     * @param realName 真实姓名 模糊匹配
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String realName) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            if (StringUtils.isNotBlank(realName)) {
                paramMap.put("realName", realName);
            }
            List<SysUserVo> sysUserVoList = sysUserService.list(paramMap);
            if (null == sysUserVoList) {
                sysUserVoList = new ArrayList<>();
            }
            return JsonResponseBuilder.buildSuccess(sysUserVoList);
        } catch (Exception e) {
            logger.error("SysUserController list 用户集合查询失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(BaseConstant.QUERY_FAIL);
    }

    /**
     * 用户启用(批量)
     *
     * @param userId 用户id(多个以逗号隔开)
     * @return
     */
    @RequestMapping(value = "/enable")
    @ResponseBody
    public Object enable(String userId) {
        try {
            if (null == userId) {
                return JsonResponseBuilder.buildFail(SysUserConstants.ENABLE_FAIL_NO_USERID);
            }
            List<String> userIdListStr = Arrays.asList(userId.split(BaseConstant.COMMA_EN));
            if (CollectionUtils.isEmpty(userIdListStr)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.ENABLE_FAIL_NO_USERID);
            }
            List<Integer> userIdList = CollectionsUtil.listStrngToInteger(userIdListStr);
            sysUserService.batchEnable(userIdList);
            return JsonResponseBuilder.buildSuccess(SysUserConstants.ENABLE_SUCCESS);
        } catch (Exception e) {
            logger.error("SysUserController enable 用户启用失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(BaseConstant.QUERY_FAIL);
    }


    /**
     * 用户停用批量
     *
     * @param userId 用户id(多个以逗号隔开)
     * @return
     */
    @RequestMapping(value = "/disable")
    @ResponseBody
    public Object disable(String userId) {
        try {
            if (null == userId) {
                return JsonResponseBuilder.buildFail(SysUserConstants.DISABLE_FAIL_NO_USERID);
            }
            List<String> userIdListStr = Arrays.asList(userId.split(BaseConstant.COMMA_EN));
            if (CollectionUtils.isEmpty(userIdListStr)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.DISABLE_FAIL_NO_USERID);
            }
            List<Integer> userIdList = CollectionsUtil.listStrngToInteger(userIdListStr);
            //超级管理员不能被停用
            if (userIdList.contains(BaseConstant.SUPER_ADMIN_USER_ID)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.DISABLE_FAIL_SUPER_ADMIN_CANNOT_DISABLE);
            }
            sysUserService.batchDisable(userIdList);
            return JsonResponseBuilder.buildSuccess(SysUserConstants.DISABLE_SUCCESS);
        } catch (Exception e) {
            logger.error("SysUserController disable 用户停用失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysUserConstants.DISABLE_FAIL);
    }

    /**
     * 删除用户
     *
     * @param userId 删除的用户id
     * @return
     */
    @RequestMapping(value = "/deleteSysUser")
    @ResponseBody
    public Object deleteSysUser(Integer userId) {
        try {
            if (null == userId) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
            }
            if (BaseConstant.SUPER_ADMIN_USER_ID == userId) {
                return JsonResponseBuilder.buildFail(SysUserConstants.DELETE_FAIL_SUPER_ADMIN_CANNOT_DELETE);
            }
            int effectRow = sysUserService.deleteById(userId);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysUserConstants.DELETE_SUCCESS);
            }
        } catch (Exception e) {
            logger.error("SysRoleController deleteSysUser 删除用户失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysUserConstants.DELETE_FAIL);
    }

    /**
     * 批量删除用户
     *
     * @param userIds 批量删除的用户id
     * @return
     */
    @RequestMapping(value = "/batchDeleteSysUser")
    @ResponseBody
    public Object batchDeleteSysUser(String userIds) {
        try {
            if (null == userIds) {
                return JsonResponseBuilder.buildFail(SysUserConstants.DELETE_FAIL_NO_USERID);
            }
            List<String> userIdListStr = Arrays.asList(userIds.split(BaseConstant.COMMA_EN));
            if (CollectionUtils.isEmpty(userIdListStr)) {
                return JsonResponseBuilder.buildFail(BaseConstant.MSG_PARAM_ERROR);
            }
            List<Integer> userIdList = CollectionsUtil.listStrngToInteger(userIdListStr);
            //超级管理员不能删除
            if (userIdList.contains(BaseConstant.SUPER_ADMIN_USER_ID)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.DELETE_FAIL_SUPER_ADMIN_CANNOT_DELETE);
            }
            int effectRow = sysUserService.batchDeleteById(userIdList);
            if (effectRow > 0) {
                return JsonResponseBuilder.buildSuccess(SysUserConstants.DELETE_SUCCESS);
            }
        } catch (Exception e) {
            logger.error("SysRoleController deleteSysUser 删除用户失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysUserConstants.DELETE_FAIL);
    }

    /**
     * 下载用户导入模板
     *
     * @return
     */
    @RequestMapping(value = "/downloadSysUserTemplate")
    @ResponseBody
    public Object downloadSysUserTemplate(Boolean isOnLine, HttpServletResponse response) {
        if (null == isOnLine) {
            isOnLine = false;
        }
        String result = BaseConstant.MSG_ERROR;
        try {
            result = ExcelUtils.downloadSysUserTemplate(isOnLine, response);
            if (BaseConstant.MSG_SUCCESS.equals(result)) {
                return BaseConstant.CODE_DOWNLOAD_SUCCESS;
            }
        } catch (Exception e) {
            logger.error("SysUserController downloadSysUserTemplate 下载用户导入模板失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(result);
    }

    /**
     * 批量导入用户
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/importUserBatch")
    @ResponseBody
    public Object importUserBatch(MultipartFile file) {
        String result = FileConstants.IMPORT_FAIL;
        try {
            if (null == file || file.isEmpty()) {
                return JsonResponseBuilder.buildSuccess(FileConstants.NO_FILE);
            }
            result = sysUserService.importUserBatch(file);
            if (StringUtils.isNotBlank(result) && result.contains(FileConstants.IMPORT_SUCCESS)) {
                return JsonResponseBuilder.buildSuccess(result);
            }
        } catch (IOException e) {
            logger.error("SysUserController importUserBatch 批量导入用户失败：" + e.getMessage());
            if (SysUserConstants.IMPORT_FAIL_NOT_SUPPORT_FILE_TYPE.equals(e.getMessage())) {
                return JsonResponseBuilder.buildFail(e.getMessage());
            }
        } catch (Exception e) {
            logger.error("SysUserController importUserBatch 批量导入用户失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(result);
    }

    /**
     * 民族列表
     *
     * @param nationName 民族名称（模糊匹配）
     * @return
     */
    @RequestMapping(value = "/listNation")
    @ResponseBody
    public Object listNation(String nationName) {
        List<String> nationList = MyConfig.nationList;
        try {
            if (StringUtils.isNotBlank(nationName)) {
                //过滤
                List<String> nationFilterList = new ArrayList<>();
                for (int i = 0; i < nationList.size(); i++) {
                    if (nationList.get(i).contains(nationName)) {
                        nationFilterList.add(nationList.get(i));
                    }
                }
                return JsonResponseBuilder.buildSuccess(nationFilterList);
            }
            return JsonResponseBuilder.buildSuccess(nationList);
        } catch (Exception e) {
            logger.error("SysUserController listNation 民族列表查询失败：" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(BaseConstant.QUERY_FAIL);
    }

}
